{% extends "base.html" %}

{% set current_menu = 'system' %}
{% set current_page = 'user_edit' if is_edit else 'user_create' %}

{% block title %}系统管理 - {{ '编辑用户' if is_edit else '添加用户' }}{% endblock %}

{% block page_title %}{{ '编辑用户' if is_edit else '添加用户' }}{% endblock %}
{% block page_subtitle %}{{ '修改用户信息和权限' if is_edit else '创建新的用户账号' }}{% endblock %}

{% block content %}
<div class="container mx-auto">
    <!-- 面包屑导航 -->
    <nav class="text-sm breadcrumbs mb-6">
        <ol class="flex items-center space-x-2">
            <li><a href="{{ url_for('main.home') }}" class="text-gray-500 hover:text-gray-700">首页</a></li>
            <li><i class="fas fa-chevron-right text-gray-400 text-xs mx-2"></i></li>
            <li><a href="{{ url_for('user.user_list') }}" class="text-gray-500 hover:text-gray-700">系统管理</a></li>
            <li><i class="fas fa-chevron-right text-gray-400 text-xs mx-2"></i></li>
            <li><a href="{{ url_for('user.user_list') }}" class="text-gray-500 hover:text-gray-700">用户管理</a></li>
            <li><i class="fas fa-chevron-right text-gray-400 text-xs mx-2"></i></li>
            <li class="text-gray-700">{{ '编辑用户' if is_edit else '添加用户' }}</li>
        </ol>
    </nav>

    <div class="bg-white rounded-lg shadow">
        <form method="POST" action="{{ url_for('user.edit_user' if is_edit else 'user.create_user', user_id=user.id if is_edit else None) }}" id="user-form">
            <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
            
            <!-- 基本信息 -->
            <div class="p-6 border-b border-gray-200">
                <h3 class="text-lg font-medium text-gray-900 mb-4">基本信息</h3>
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <label for="name" class="block text-sm font-medium text-gray-700 mb-1">
                            用户姓名 <span class="text-red-500">*</span>
                        </label>
                        <input type="text" id="name" name="name" required
                               class="w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
                               value="{{ user.name if is_edit else '' }}">
                        {% if form_errors.name %}
                        <p class="mt-1 text-sm text-red-600">{{ form_errors.name[0] }}</p>
                        {% endif %}
                    </div>
                    
                    <div>
                        <label for="username" class="block text-sm font-medium text-gray-700 mb-1">
                            用户名 <span class="text-red-500">*</span>
                        </label>
                        <input type="text" id="username" name="username" required
                               class="w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
                               value="{{ user.username if is_edit else '' }}"
                               {% if is_edit %}readonly{% endif %}>
                        {% if form_errors.username %}
                        <p class="mt-1 text-sm text-red-600">{{ form_errors.username[0] }}</p>
                        {% endif %}
                        {% if is_edit %}
                        <p class="mt-1 text-sm text-gray-500">用户名创建后不可修改</p>
                        {% endif %}
                    </div>
                    
                    <div>
                        <label for="password" class="block text-sm font-medium text-gray-700 mb-1">
                            密码 {% if not is_edit %}<span class="text-red-500">*</span>{% endif %}
                        </label>
                        <input type="password" id="password" name="password" {% if not is_edit %}required{% endif %}
                               class="w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
                        {% if form_errors.password %}
                        <p class="mt-1 text-sm text-red-600">{{ form_errors.password[0] }}</p>
                        {% endif %}
                        {% if is_edit %}
                        <p class="mt-1 text-sm text-gray-500">留空表示不修改密码</p>
                        {% endif %}
                    </div>
                    
                    <div>
                        <label for="confirm_password" class="block text-sm font-medium text-gray-700 mb-1">
                            确认密码 {% if not is_edit %}<span class="text-red-500">*</span>{% endif %}
                        </label>
                        <input type="password" id="confirm_password" name="confirm_password" {% if not is_edit %}required{% endif %}
                               class="w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
                        {% if form_errors.confirm_password %}
                        <p class="mt-1 text-sm text-red-600">{{ form_errors.confirm_password[0] }}</p>
                        {% endif %}
                    </div>
                    
                    <div>
                        <label for="department" class="block text-sm font-medium text-gray-700 mb-1">
                            部门
                        </label>
                        <select id="department" name="department"
                                class="w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
                            <option value="">请选择部门</option>
                            {% for department in departments %}
                            <option value="{{ department }}" {% if is_edit and user.department == department %}selected{% endif %}>{{ department }}</option>
                            {% endfor %}
                        </select>
                        {% if form_errors.department %}
                        <p class="mt-1 text-sm text-red-600">{{ form_errors.department[0] }}</p>
                        {% endif %}
                    </div>
                    
                    <div>
                        <label for="position" class="block text-sm font-medium text-gray-700 mb-1">
                            职位
                        </label>
                        <select id="position" name="position"
                                class="w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
                            <option value="">请选择职位</option>
                            {% for position in positions %}
                            <option value="{{ position }}" {% if is_edit and user.position == position %}selected{% endif %}>{{ position }}</option>
                            {% endfor %}
                        </select>
                        {% if form_errors.position %}
                        <p class="mt-1 text-sm text-red-600">{{ form_errors.position[0] }}</p>
                        {% endif %}
                    </div>
                    
                    <div>
                        <label for="hire_date" class="block text-sm font-medium text-gray-700 mb-1">
                            入职时间
                        </label>
                        <input type="date" id="hire_date" name="hire_date"
                               class="w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
                               value="{{ user.hire_date.strftime('%Y-%m-%d') if is_edit and user.hire_date else '' }}">
                        {% if form_errors.hire_date %}
                        <p class="mt-1 text-sm text-red-600">{{ form_errors.hire_date[0] }}</p>
                        {% endif %}
                    </div>
                    
                    <div>
                        <label for="phone" class="block text-sm font-medium text-gray-700 mb-1">
                            联系电话
                        </label>
                        <input type="text" id="phone" name="phone"
                               class="w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
                               value="{{ user.phone if is_edit else '' }}">
                        {% if form_errors.phone %}
                        <p class="mt-1 text-sm text-red-600">{{ form_errors.phone[0] }}</p>
                        {% endif %}
                    </div>
                    
                    <div class="md:col-span-2">
                        <label for="email" class="block text-sm font-medium text-gray-700 mb-1">
                            电子邮箱
                        </label>
                        <input type="email" id="email" name="email"
                               class="w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
                               value="{{ user.email if is_edit else '' }}">
                        {% if form_errors.email %}
                        <p class="mt-1 text-sm text-red-600">{{ form_errors.email[0] }}</p>
                        {% endif %}
                    </div>
                </div>
            </div>
            
            <!-- 账号设置 -->
            <div class="p-6 border-b border-gray-200">
                <h3 class="text-lg font-medium text-gray-900 mb-4">账号设置</h3>
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">
                            用户状态
                        </label>
                        <div class="mt-1 space-y-2">
                            <div class="flex items-center">
                                <input id="status-active" name="is_active" type="radio" value="true" 
                                       class="focus:ring-primary h-4 w-4 text-primary border-gray-300"
                                       {% if not is_edit or user.is_active %}checked{% endif %}>
                                <label for="status-active" class="ml-3 block text-sm font-medium text-gray-700">
                                    活跃
                                </label>
                            </div>
                            <div class="flex items-center">
                                <input id="status-inactive" name="is_active" type="radio" value="false" 
                                       class="focus:ring-primary h-4 w-4 text-primary border-gray-300"
                                       {% if is_edit and not user.is_active %}checked{% endif %}>
                                <label for="status-inactive" class="ml-3 block text-sm font-medium text-gray-700">
                                    禁用
                                </label>
                            </div>
                        </div>
                        {% if form_errors.is_active %}
                        <p class="mt-1 text-sm text-red-600">{{ form_errors.is_active[0] }}</p>
                        {% endif %}
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">
                            用户角色
                        </label>
                        <div class="mt-1 space-y-2">
                            <div class="flex items-center">
                                <input id="role-user" name="role" type="radio" value="user" 
                                       class="focus:ring-primary h-4 w-4 text-primary border-gray-300"
                                       {% if not is_edit or user.role == 'user' %}checked{% endif %}>
                                <label for="role-user" class="ml-3 block text-sm font-medium text-gray-700">
                                    普通用户
                                </label>
                            </div>
                            <div class="flex items-center">
                                <input id="role-admin" name="role" type="radio" value="admin" 
                                       class="focus:ring-primary h-4 w-4 text-primary border-gray-300"
                                       {% if is_edit and user.role == 'admin' %}checked{% endif %}>
                                <label for="role-admin" class="ml-3 block text-sm font-medium text-gray-700">
                                    管理员
                                </label>
                            </div>
                        </div>
                        {% if form_errors.role %}
                        <p class="mt-1 text-sm text-red-600">{{ form_errors.role[0] }}</p>
                        {% endif %}
                    </div>
                </div>
            </div>
            
            <!-- 权限设置 -->
            <div class="p-6 border-b border-gray-200">
                <h3 class="text-lg font-medium text-gray-900 mb-4">权限设置</h3>
                
                <div class="space-y-4">
                    <div>
                        <h4 class="text-md font-medium text-gray-800 mb-2">系统功能权限</h4>
                        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
                            <div class="flex items-center">
                                <input id="perm-dashboard" name="permissions" type="checkbox" value="dashboard" 
                                       class="focus:ring-primary h-4 w-4 text-primary border-gray-300 rounded"
                                       {% if is_edit and 'dashboard' in user_permissions %}checked{% endif %}>
                                <label for="perm-dashboard" class="ml-3 block text-sm text-gray-700">
                                    查看仪表盘
                                </label>
                            </div>
                            <div class="flex items-center">
                                <input id="perm-project" name="permissions" type="checkbox" value="project" 
                                       class="focus:ring-primary h-4 w-4 text-primary border-gray-300 rounded"
                                       {% if is_edit and 'project' in user_permissions %}checked{% endif %}>
                                <label for="perm-project" class="ml-3 block text-sm text-gray-700">
                                    项目管理
                                </label>
                            </div>
                            <div class="flex items-center">
                                <input id="perm-customer" name="permissions" type="checkbox" value="customer" 
                                       class="focus:ring-primary h-4 w-4 text-primary border-gray-300 rounded"
                                       {% if is_edit and 'customer' in user_permissions %}checked{% endif %}>
                                <label for="perm-customer" class="ml-3 block text-sm text-gray-700">
                                    客户管理
                                </label>
                            </div>
                            <div class="flex items-center">
                                <input id="perm-system" name="permissions" type="checkbox" value="system" 
                                       class="focus:ring-primary h-4 w-4 text-primary border-gray-300 rounded"
                                       {% if is_edit and 'system' in user_permissions %}checked{% endif %}>
                                <label for="perm-system" class="ml-3 block text-sm text-gray-700">
                                    系统管理
                                </label>
                            </div>
                            <div class="flex items-center">
                                <input id="perm-report" name="permissions" type="checkbox" value="report" 
                                       class="focus:ring-primary h-4 w-4 text-primary border-gray-300 rounded"
                                       {% if is_edit and 'report' in user_permissions %}checked{% endif %}>
                                <label for="perm-report" class="ml-3 block text-sm text-gray-700">
                                    报表统计
                                </label>
                            </div>
                            <div class="flex items-center">
                                <input id="perm-setting" name="permissions" type="checkbox" value="setting" 
                                       class="focus:ring-primary h-4 w-4 text-primary border-gray-300 rounded"
                                       {% if is_edit and 'setting' in user_permissions %}checked{% endif %}>
                                <label for="perm-setting" class="ml-3 block text-sm text-gray-700">
                                    系统设置
                                </label>
                            </div>
                        </div>
                    </div>
                    
                    <div>
                        <h4 class="text-md font-medium text-gray-800 mb-2">数据访问权限</h4>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                            <div class="flex items-center">
                                <input id="data-all" name="data_permissions" type="radio" value="all" 
                                       class="focus:ring-primary h-4 w-4 text-primary border-gray-300"
                                       {% if is_edit and user_data_permission == 'all' %}checked{% endif %}>
                                <label for="data-all" class="ml-3 block text-sm text-gray-700">
                                    全部数据
                                </label>
                            </div>
                            <div class="flex items-center">
                                <input id="data-department" name="data_permissions" type="radio" value="department" 
                                       class="focus:ring-primary h-4 w-4 text-primary border-gray-300"
                                       {% if is_edit and user_data_permission == 'department' %}checked{% endif %}>
                                <label for="data-department" class="ml-3 block text-sm text-gray-700">
                                    本部门数据
                                </label>
                            </div>
                            <div class="flex items-center">
                                <input id="data-self" name="data_permissions" type="radio" value="self" 
                                       class="focus:ring-primary h-4 w-4 text-primary border-gray-300"
                                       {% if is_edit and user_data_permission == 'self' %}checked{% endif %}>
                                <label for="data-self" class="ml-3 block text-sm text-gray-700">
                                    个人数据
                                </label>
                            </div>
                            <div class="flex items-center">
                                <input id="data-custom" name="data_permissions" type="radio" value="custom" 
                                       class="focus:ring-primary h-4 w-4 text-primary border-gray-300"
                                       {% if is_edit and user_data_permission == 'custom' %}checked{% endif %}>
                                <label for="data-custom" class="ml-3 block text-sm text-gray-700">
                                    自定义数据
                                </label>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 提交按钮 -->
            <div class="px-6 py-4 bg-gray-50 flex justify-end">
                <a href="{{ url_for('user.user_list') }}" class="px-4 py-2 bg-gray-300 text-gray-800 rounded-md hover:bg-gray-400 transition">
                    取消
                </a>
                <button type="submit" class="ml-3 px-4 py-2 bg-primary text-white rounded-md hover:bg-blue-600 transition">
                    {{ '保存修改' if is_edit else '创建用户' }}
                </button>
            </div>
        </form>
    </div>
</div>
{% endblock %}

{% block extra_js %}
{{ super() }}
<script>
    // 表单验证
    document.getElementById('user-form').addEventListener('submit', function(e) {
        const password = document.getElementById('password').value;
        const confirmPassword = document.getElementById('confirm_password').value;
        
        // 如果是编辑模式且密码为空，则跳过密码验证
        if (!('{{ is_edit }}' === 'True') || password) {
            if (password !== confirmPassword) {
                e.preventDefault();
                showFlashMessage('两次输入的密码不一致，请重新输入！', 'error');
                document.getElementById('password').focus();
                return false;
            }
            
            if (password.length < 6) {
                e.preventDefault();
                showFlashMessage('密码长度不能少于6位！', 'error');
                document.getElementById('password').focus();
                return false;
            }
        }
        
        // 验证邮箱格式
        const email = document.getElementById('email').value;
        if (email && !validateEmail(email)) {
            e.preventDefault();
            showFlashMessage('请输入有效的邮箱地址！', 'error');
            document.getElementById('email').focus();
            return false;
        }
        
        // 验证手机号格式
        const phone = document.getElementById('phone').value;
        if (phone && !validatePhone(phone)) {
            e.preventDefault();
            showFlashMessage('请输入有效的手机号码！', 'error');
            document.getElementById('phone').focus();
            return false;
        }
        
        return true;
    });
    
    // 验证邮箱格式
    function validateEmail(email) {
        const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return re.test(email);
    }
    
    // 验证手机号格式
    function validatePhone(phone) {
        const re = /^1[3-9]\d{9}$/;
        return re.test(phone);
    }
    
    // 当选择管理员角色时，自动勾选所有权限
    document.getElementById('role-admin').addEventListener('change', function() {
        if (this.checked) {
            // 勾选所有系统功能权限
            const permissionCheckboxes = document.querySelectorAll('input[name="permissions"]');
            permissionCheckboxes.forEach(checkbox => {
                checkbox.checked = true;
            });
            
            // 选择全部数据权限
            document.getElementById('data-all').checked = true;
        }
    });
    
    // 当选择普通用户角色时，取消勾选系统管理权限
    document.getElementById('role-user').addEventListener('change', function() {
        if (this.checked) {
            // 取消勾选系统管理权限
            const systemPermission = document.getElementById('perm-system');
            if (systemPermission) {
                systemPermission.checked = false;
            }
            
            // 取消勾选系统设置权限
            const settingPermission = document.getElementById('perm-setting');
            if (settingPermission) {
                settingPermission.checked = false;
            }
            
            // 如果之前是全部数据权限，则改为本部门数据权限
            if (document.getElementById('data-all').checked) {
                document.getElementById('data-department').checked = true;
            }
        }
    });
</script>
{% endblock %}